package com.blue.firecat.serivce.impl;

import com.alibaba.fastjson.JSON;
import com.blue.firecat.contants.Contants;
import com.blue.firecat.contants.Result;
import com.blue.firecat.dao.UserDao;
import com.blue.firecat.entity.User;
import com.blue.firecat.entity.UserExample;
import com.blue.firecat.enums.ErrorEnum;
import com.blue.firecat.enums.UserStatusEnum;
import com.blue.firecat.enums.UserTypeEnum;
import com.blue.firecat.serivce.UserService;
import com.blue.firecat.utils.IdCardCheckUtil;
import com.blue.firecat.utils.email.EmailUtils;
import com.blue.firecat.utils.property.PropertiesUtil;
import com.blue.firecat.vo.UserVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @描述 用户基本业务逻辑
 * @时间 2017-6-22 13:43
 * @作者 肖亦鸣
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Override
    public Result<User> selectByPrimaryKey(Long id, User loginUser) {
        Result result = new Result();
        User user = userDao.selectByPrimaryKey(id);
        if (user == null) {
            result.setCode(ErrorEnum.USER_DOES_NOT_EXIST);
            return result;
        }
        //如果是本人或者是管理员,可以看到所有信息
        if (user.getId().equals(loginUser.getId()) || loginUser.getType().equals(UserTypeEnum.ADMIN.getCode())) {
        } else {
            user.setIdCard("******************");
            user.setUserName("******************");
            user.setOperate("******************");
            user.setBankCard("******************");
            user.setPassword("******************");
        }
        result.setData(user);
        return result;
    }

    @Override
    public Result<List<User>> selectByExample(User user) {
        Result<List<User>> result = new Result<>();
        if (Contants.verifyAuthority(user, result)) return result;
        List<User> users = userDao.selectByExample(null);
        result.setData(users);
        return result;
    }

    @Override
    public Result<User> insertSelective(User user, User userLogin) {
        Result result = new Result();
        //1.必须是管理员
        if (Contants.verifyAuthority(userLogin, result)) return result;
        boolean idNum = IdCardCheckUtil.isIdNum(user.getIdCard());
        //如果不是
        if (!idNum) {
            result.setCode(ErrorEnum.USER_ID_ERROR);
            return result;
        }
        user.setCreateTime(new Date());
        user.setStatus(UserStatusEnum.ACTIVATED.getCode());
        user.setPassword("123456");
        //校验用户存在不存在
        UserExample example = new UserExample();
        example.getOredCriteria().add(example.createCriteria().andUserNameEqualTo(user.getUserName()));
        List<User> users = userDao.selectByExample(example);
        if (CollectionUtils.isNotEmpty(users)) {
            result.setCode(ErrorEnum.USER_NAME_HAS);
            return result;
        }
        example = new UserExample();
        example.getOredCriteria().add(example.createCriteria().andIdCardEqualTo(user.getIdCard()));
        users = userDao.selectByExample(example);
        if (CollectionUtils.isNotEmpty(users)) {
            result.setCode(ErrorEnum.USER_ID_CARD_HAS);
            return result;
        }

        int i = userDao.insertSelective(user);
        if (i == 0) {
            result.setCode(ErrorEnum.USER_CREATE_ERROR);
        }
        result.setData(user);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EmailUtils emailUtils = new EmailUtils("", user.getEmail(), user.getTypeString() + ",您的初始化密码为:" + user.getPassword());
                    emailUtils.send(9);
                } finally {
                }
            }
        }).start();
        return result;
    }

    @Override
    public Result<User> updateByPrimaryKeySelective(User record) {
        Result result = new Result();
        int i = userDao.updateByPrimaryKeySelective(record);
        result.setMessage(ErrorEnum.USER_MODIFY_SUCCESS.getValue());
        if (i == 0) {
            result.setCode(ErrorEnum.USER_MODIFY_ERROR);
        }
        result.setData(userDao.selectByPrimaryKey(record.getId()));
        return result;

    }

    @Override
    public Result<User> deleteByPrimaryKey(User user, Long id) {
        Result<User> result = new Result<>();
        if (Contants.verifyAuthority(user, result)) return result;
        int i = userDao.deleteByPrimaryKey(id);
        if (i == 0) {
            result.setCode(ErrorEnum.USER_DOES_NOT_EXIST);
        }
        return result;
    }

    @Override
    public List<User> selectByExample(UserExample example) {
        return userDao.selectByExample(example);
    }

    @Override
    public Result<User> login(User user) {
        Result<User> result = new Result<>();
        Pattern pattern = Pattern.compile("[0-9]*");
        boolean isNumber = pattern.matcher(user.getUserName()).matches();
        if (isNumber) {
            user.setPhone(Long.valueOf(user.getUserName()));
        }
        user.setEmail(user.getUserName());
        User uu = userDao.login(user);
        //密码错误或者用户不存在
        if (uu == null) {
            result.setCode(ErrorEnum.USER_PASSWORD_ERROR.getCode());
            result.setData(user);
            return result;
        }
        //已停用
        if (!uu.getStatus().equals(UserStatusEnum.ACTIVATED.getCode())) {
            result.setCode(ErrorEnum.USER_IS_NOT_ENABLED.getCode());
        }
        result.setData(uu);
        return result;
    }

    @Override
    public Result<List<User>> getAllBeater() {
        Result<List<User>> result = new Result<>();
        UserExample example = new UserExample();
        example.getOredCriteria().add(example.createCriteria().andTypeEqualTo(UserTypeEnum.BEATER.getCode())
                .andStatusEqualTo(UserStatusEnum.ACTIVATED.getCode()));
        List<User> users = userDao.selectByExample(example);
        result.setData(users);
        return result;
    }

    @Override
    public Result<List<User>> getAllCustom() {
        Result<List<User>> result = new Result<>();
        UserExample example = new UserExample();
        example.getOredCriteria().add(example.createCriteria().andTypeEqualTo(UserTypeEnum.CUSTOM_SERVICE.getCode())
                .andStatusEqualTo(UserStatusEnum.ACTIVATED.getCode()));
        List<User> users = userDao.selectByExample(example);
        result.setData(users);
        return result;
    }

    @Override
    public Result<User> stopUser(User user, Long userId, Integer status) {
        Result<User> result = new Result<>();
        if (Contants.verifyAuthority(user, result)) return result;
        User u = new User();
        u.setId(userId);
        u.setStatus(status);
        int i = userDao.updateByPrimaryKeySelective(u);
        if (i == 0) {
            result.setCode(ErrorEnum.USER_DOES_NOT_EXIST);
        }
        if (status == UserStatusEnum.ACTIVATED.getCode()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        EmailUtils emailUtils = new EmailUtils("", userDao.selectByPrimaryKey(userId).getEmail(),
                                "");
                        emailUtils.send(10);
                    } finally {
                    }
                }
            }).start();
        }
        return result;
    }

    @Override
    public Result<User> updatePassword(UserVo userVo) {
        Result<User> result = new Result<>();
        if (StringUtils.isEmpty(userVo.getPassword())
                || StringUtils.isEmpty(userVo.getP1())
                || StringUtils.isEmpty(userVo.getP2())) {
            result.setCode(ErrorEnum.USER_PASSWORD_IS_EMPTY_ERROR);
            return result;
        }
        if (!userVo.getP1().equals(userVo.getP2())) {
            result.setCode(ErrorEnum.USER_TWO_PASSWORD_ERROR);
            return result;
        }
        User user = userDao.selectByPrimaryKey(userVo.getId());
        if (!user.getPassword().equals(userVo.getPassword())) {
            result.setCode(ErrorEnum.USER_PASSWORD_ERROR);
            return result;
        }
        user.setPassword(userVo.getP2());
        userDao.updateByPrimaryKey(user);

        return result;
    }

    @Override
    public Result<User> register(User user) {
        Result<User> result = new Result<>();
        boolean idNum = IdCardCheckUtil.isIdNum(user.getIdCard());
        //如果不是
        if (!idNum) {
            result.setCode(ErrorEnum.USER_ID_ERROR);
            return result;
        }
        //校验用户存在不存在
        UserExample example = new UserExample();
        example.getOredCriteria().add(example.createCriteria().andUserNameEqualTo(user.getUserName()));
        List<User> users = userDao.selectByExample(example);
        if (CollectionUtils.isNotEmpty(users)) {
            result.setCode(ErrorEnum.USER_NAME_HAS);
            return result;
        }
        example = new UserExample();
        example.getOredCriteria().add(example.createCriteria().andIdCardEqualTo(user.getIdCard()));
        users = userDao.selectByExample(example);
        if (CollectionUtils.isNotEmpty(users)) {
            result.setCode(ErrorEnum.USER_ID_CARD_HAS);
            return result;
        }

        user.setType(UserTypeEnum.BEATER.getCode());
        user.setStatus(UserStatusEnum.TERMINATED.getCode());
        user.setCreateTime(new Date());
        int i = userDao.insertSelective(user);
        if (i > 0) {
            result.setCode(ErrorEnum.USER_GOOD);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    user.setPassword("*******");
                    EmailUtils emailUtils = new EmailUtils("", PropertiesUtil.getProperty("username"), JSON.toJSONString(user));
                    emailUtils.send(8);
                } finally {
                }
            }
        }).start();
        return result;
    }

    @Override
    public Result<User> forgetPassword(User user) {
        Result<User> result = new Result<>();

        UserExample example = new UserExample();
        example.getOredCriteria().add(example.createCriteria().andEmailEqualTo(user.getEmail()).andIdCardEqualTo(user.getIdCard()));
        List<User> users = userDao.selectByExample(example);
        if (CollectionUtils.isEmpty(users)) {
            result.setCode(ErrorEnum.USER_DOES_NOT_EXIST1);
            return result;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EmailUtils emailUtils = new EmailUtils("", user.getEmail(), users.get(0).getPassword());
                    emailUtils.send(5);
                } finally {
                }
            }
        }).start();
        result.setCode(ErrorEnum.USER_PASSWORD_SEND_EMAIL);
        return result;
    }


}
